﻿using PARK.Common.Const;
using PARK.Common.Core.Manager;
using PARK.DataEncryption;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.System.Interfaces.Permission;
using PARK.System.Interfaces.System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using PARK.CardAcct.Interfaces;
using System.IO;
using PARK.CardAcct.Entitys.Dto.Wechat;
using PARK.Common.WeChat;
using PARK.CardAcct.Entitys;
using Yitter.IdGenerator;
using System.Net;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Linq;
using Newtonsoft.Json;
using KYSharp.SM;
using PARK.BussinCache.Interfaces;
using JNPF.Logging;
using PARK.OAuth.Service.Dto;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using System.Text.RegularExpressions;
using PARK.OAuth.Entitys;

namespace PARK.OAuth.Service
{
    /// <summary>
    /// 业务实现：身份认证模块
    /// </summary>
    [ApiDescriptionSettings(Tag = "Wechat", Name = "OAuth", Order = 160)]
    [Route("api/Wechat/[controller]")]
    public class WechatAuthService : IDynamicApiController, ITransient
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IUsersService _userService; // 用户表仓储
        private readonly ISysConfigService _sysConfigService; //系统配置仓储        
        private readonly IUserManager _userManager; // 用户管理
        private readonly ISysCacheService _sysCacheService;
        private readonly IEmployeeWechatService _employeeWechatService; // 用户表仓储 
        private readonly SqlSugarScope _db;
        private readonly ITenant _tenant;
        private readonly IParkCacheRepository _parkCacheRepository;

        //阿里云短信参数
        private string _keyId = "LTAI5t5zafokTAvZapsLuE4r"; //AccessKey ID
        private string _keySecret = "0BPbtJYYfbH1AiWGf0e69ZOcvLfWnr"; //AccessKey Secret
        private string _templateId = "SMS_466740018"; //模板ID

        /// <summary>
        /// 初始化一个<see cref="OAuthService"/>类型的新实例
        /// </summary>
        public WechatAuthService(IUsersService userService,
            IHttpContextAccessor httpContextAccessor,
            ISysConfigService sysConfigService,          
            IUserManager userManager,
            ISysCacheService sysCacheService,
            ISqlSugarClient db,
            IEmployeeWechatService employeeWechatService,
            IParkCacheRepository parkCacheRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _userService = userService;
            _sysConfigService = sysConfigService;           
            _userManager = userManager;
            _sysCacheService = sysCacheService;
            _db = (SqlSugarScope)db;
            _tenant = (ITenant)_db;
            _employeeWechatService = employeeWechatService;
            _parkCacheRepository = parkCacheRepository;
        }

        #region 小程序用户授权
        /// <summary>
        /// 小程序用户授权
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        [AllowAnonymous]
        [Consumes("application/x-www-form-urlencoded")]
        public async Task<WeChatUserLoginOutput> Login(string code)
        {
            WeChatUserLoginOutput Output = new WeChatUserLoginOutput();
            try
            {
                string tenantDbName = PARK.App.Configuration["ConnectionStrings:DBName"];
                string tenantId = PARK.App.Configuration["ConnectionStrings:ConfigId"];
                WechatUser Wu = new WechatUser();
                string appid = $"{App.Configuration["OAuth:routine:appid"]}";
                string appsecret = $"{App.Configuration["OAuth:routine:appSecret"]}";
                setlog("------code:" + code + ";APPID:" + appid + ";APPSECRET:" + appsecret);
                var ret = Wu.GetOpenidAndAccessTokenFromCode(code, appid, appsecret);
                if (ret > 0 && Wu != null && !string.IsNullOrEmpty(Wu.Openid))
                {
                    setlog("获取到用户OpenId:" + Wu.Openid);

                    var eyWechats = await _db.Queryable<EmployeeWechatEntity>().Where(p => p.OpenId == Wu.Openid && p.IsAudit==1).ToListAsync();
                    if (eyWechats != null && eyWechats.Count>0) 
                    {
                        var entity = new EmployeeWechatEntity();
                        var _Wechats = eyWechats.Where(p => p.IsMain == 1).ToList();
                        if(_Wechats!=null && _Wechats.Count > 0)
                        {
                            entity = _Wechats[0];
                        }
                        else
                        {
                            entity = eyWechats[0];
                        }
                        entity.OpenId = Wu.Openid;
                        setlog("获取到用户->当前用户:" + JsonConvert.SerializeObject(entity));
                        var eyeInfo = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == entity.EmployeeId);
                        if (eyeInfo.AccStatus == 1 || eyeInfo.AccStatus == 3)
                        {
                            #region 生成token
                            //登录成功时 判断单点登录信息            
                            var tokenTimeout = 129600;// await _sysConfigService.GetInfo("SysConfig", "tokentimeout");//token过期时间
                                                      // 生成Token令牌
                            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                                {
                                        { ClaimConst.CLAINM_USERID, entity.WId},
                                        { ClaimConst.CLAINM_ACCOUNT, entity.OpenId },
                                        { ClaimConst.CLAINM_REALNAME, entity.RealName },
                                        { ClaimConst.CLAINM_ADMINISTRATOR, 0 },
                                        { ClaimConst.TENANT_ID, tenantId },
                                        { ClaimConst.TENANT_DB_NAME, tenantDbName },
                                        { ClaimConst.CLAINM_USER_KIND, "1" } //C端用户
                                }, tokenTimeout);
                            var httpContext = _httpContextAccessor.HttpContext;
                            // 设置Swagger自动登录
                            httpContext.SigninToSwagger(accessToken);
                            // 生成刷新Token令牌
                            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 30);
                            // 设置刷新Token令牌
                            httpContext.Response.Headers["x-access-token"] = refreshToken;
                            #endregion

                            //检测是否启用人脸
                            var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(entity.CompanyId);
                            if (_appInfo != null && _appInfo.uni_is > 0)
                            {
                                Output.isUseface = 1;  //启用
                            }
                            else
                            {
                                Output.isUseface = 0; //不启用
                            }
                            Output.isUseface = 0; //不启用
                            //已绑定,账户状态可用
                            Output.LoginRet = 1;
                            Output.LoginMsg = "已认证通过";
                            Output.Oauser = entity;
                            Output.token = "Bearer " + accessToken;
                            Output.expireTime = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd HH:mm:ss");
                            Output.OpenId = Wu.Openid;
                            Output.authTsMenu = eyeInfo.AuthTsMenu;
                        }
                        else
                        {
                            //账户状态,当前不可用
                            Output.LoginRet = 0;
                            Output.LoginMsg = "所绑卡户状态不可用";
                            Output.Oauser = entity;
                            Output.token = "";
                            Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                            Output.OpenId = Wu.Openid;
                            Output.authTsMenu = 0;
                        }
                    }
                    else
                    {
                        eyWechats = await _db.Queryable<EmployeeWechatEntity>().Where(p => p.OpenId == Wu.Openid).ToListAsync();
                        if (eyWechats != null && eyWechats.Count>0)
                        {
                            var entity = eyWechats[0];
                            entity.OpenId = Wu.Openid;
                            //已绑定
                            Output.LoginRet = 0;
                            Output.LoginMsg = "未认证,请先认证身份";
                            Output.token = "";
                            Output.Oauser = entity;
                            Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                            Output.OpenId = Wu.Openid;
                            Output.authTsMenu = 0;
                        }
                        else
                        {
                            var entity = new EmployeeWechatEntity();
                            entity.OpenId = Wu.Openid; //微信公众号openId
                            entity.Create();
                            entity.IsMain = 1;
                            entity.WId = YitIdHelper.NextId().ToString();
                            entity.IsDeleted = 0;
                            await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                            Output.LoginRet = 0;
                            Output.LoginMsg = "请认证身份";
                            Output.Oauser = entity;
                            Output.token = "";
                            Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                            Output.OpenId = Wu.Openid;
                            Output.authTsMenu = 0;
                        }
                    }
                }
                else
                {
                    Output.LoginRet = -1;
                    Output.LoginMsg = "获取用户微信信息失败";
                    Output.token = "";
                    Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                    Output.authTsMenu = 0;
                }
            }
            catch (Exception ex)
            {
                Output.LoginRet = 0;
                Output.LoginMsg = "登入异常";
                Output.token = "";
                Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                Output.authTsMenu = 0;
                new LoggEx().errlog("WeChatUserSignin()->登入异常:" + ex.ToString());
            }
            new LoggEx().Info("WeChatUserSignin()->LoginRet:" + Output.LoginRet + ",LoginMsg:" + Output.LoginMsg);
            return Output;
        }
        #endregion

        #region 发送验证码
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="appkey"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost("SendCodeEx")]
        [AllowAnonymous]
        [Consumes("application/x-www-form-urlencoded")]
        public async Task<WeChatUserLoginOutput> SendCodeEx(string appkey, string phone)
        {
            WeChatUserLoginOutput Output = new WeChatUserLoginOutput();
            //检测手机号是否为系统中存在的
            var Paras = new List<SugarParameter>();
            SM4Utils sm4 = new SM4Utils();
            sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
            sm4.hexString = false;
            var MobilePhoneSf = sm4.Encrypt_ECB(phone);

            //生成随机6位数字
            var _code = DateUt.GenerateRandomDigits(6);

            StringBuilder _dbSql = new StringBuilder("select 0 from dbo.base_employee ");
            _dbSql.AppendFormat(" where MobilePhoneSf ='{0}' and isnull(F_DeleteMark,0)=0", MobilePhoneSf);
            var tb = await _db.Ado.GetDataTableAsync(_dbSql.ToString(), Paras);
            if (tb != null && tb.Rows.Count > 0 && appkey == "3yl6WoNm4HQTRd7PgFs51LY371Sutv8n")// 
            {
                SmsModel smsModel = new SmsModel()
                {
                    keyId = _keyId,
                    keySecret = _keySecret,
                    mobileAli = phone,
                    templateId = _templateId,
                    signName = "长安通集团用户",
                    templateParamAli = "{\"code\":\"" + _code + "\"}"
                };
                var sendResult = SendSmsByAli(smsModel);
                if (sendResult.Code == "OK")
                {
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    //处理手机号
                    var _PendPhone = Regex.Replace(phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                    //加密手机号
                    var _PendPhoneSf = sm4.Encrypt_ECB(phone);
                    //成功写入数据库
                    var _WcAuthCodeEntity = new WcAuthCodeEntity();
                    _WcAuthCodeEntity.Create();
                    _WcAuthCodeEntity.RequestId = sendResult.RequestId;
                    _WcAuthCodeEntity.code = _code;
                    _WcAuthCodeEntity.phone = _PendPhone;
                    _WcAuthCodeEntity.phoneSf = _PendPhoneSf;
                    _WcAuthCodeEntity.IsUsed = 0;
                    var isOk = await _db.Insertable(_WcAuthCodeEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(isOk > 0))
                    {
                        Output.LoginRet = 0;
                        Output.LoginMsg = "请求失败,请重试！";
                    }
                    else
                    {
                        Output.LoginRet = 1;
                        Output.LoginMsg = "发送成功";
                    }
                }
                else
                {
                    Output.LoginRet = -1;
                    Output.LoginMsg = MessageHandle(sendResult.Code);
                }
                Output.Oauser = null;
                Output.token = null;
                Output.expireTime = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd HH:mm:ss");
                setlog("手机号->" + phone + ",发送短信验证码->:" + JsonConvert.SerializeObject(Output));
            }
            else
            {
                Output.LoginRet = 0;
                Output.LoginMsg = "禁止使用";
                Output.Oauser = null;
                Output.token = null;
                Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
            }
            return Output;
        }
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost("SendCode")]
        [AllowAnonymous]
        [Consumes("application/x-www-form-urlencoded")]
        public async Task<WeChatUserLoginOutput> SendCode(string phone)
        {
            WeChatUserLoginOutput Output = new WeChatUserLoginOutput();
            //检测手机号是否为系统中存在的
            var Paras = new List<SugarParameter>();
            SM4Utils sm4 = new SM4Utils();
            sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
            sm4.hexString = false;
            var MobilePhoneSf = sm4.Encrypt_ECB(phone);

            StringBuilder _dbSql = new StringBuilder("select 0 from dbo.base_employee ");
            _dbSql.AppendFormat(" where MobilePhoneSf ='{0}' and isnull(F_DeleteMark,0)=0", MobilePhoneSf);
            var tb = await _db.Ado.GetDataTableAsync(_dbSql.ToString(), Paras);
            if (tb != null && tb.Rows.Count >0)
            {
                WebRequest request = WebRequest.Create("https://webapi.sms.mob.com/sms/sendmsg");
                request.Proxy = null;
                request.Credentials = CredentialCache.DefaultCredentials;
                ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
                byte[] bs = Encoding.UTF8.GetBytes("appkey=368ee2f379384&phone=" + phone + "&zone=86&templateCode=3076901");
                request.Method = "Post";
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                Output.LoginRet = 1;
                Output.LoginMsg = responseFromServer;
                Output.Oauser = null;
                Output.token = null;
                Output.expireTime = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd HH:mm:ss");
                setlog("手机号->" + phone + ",发送短信验证码->:" + JsonConvert.SerializeObject(Output));
            }
            else
            {
                Output.LoginRet = 0;
                Output.LoginMsg = "禁止使用";
                Output.Oauser = null;
                Output.token = null;
                Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
            }
            return Output;
        }
        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost("VerifyCode")]
        [AllowAnonymous]
        [Consumes("application/x-www-form-urlencoded")]
        public async Task<WeChatUserLoginOutput> VerifyCode(string phone,string code)
        {
            WeChatUserLoginOutput Output = new WeChatUserLoginOutput();
            setlog("手机号->" + phone + ",验证码->" + code + ",进行验证->:" + JsonConvert.SerializeObject(Output));
            try
            {
                if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(code) || phone.Length < 11)
                {
                    Output.LoginRet = -1;
                    Output.LoginMsg = "传入参数错误";
                }
                else
                {
                    //加密处理手机号
                    SM4Utils sm4 = new SM4Utils();
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    //加密手机号
                    var _PendPhoneSf = sm4.Encrypt_ECB(phone);
                    var _WcAuthCode = await _db.Queryable<WcAuthCodeEntity>().Where(p => p.phoneSf == _PendPhoneSf && p.code == code && p.CreatorTime >= DateTime.Now.AddMinutes(-5) && p.IsUsed == 0).FirstAsync();
                    if (_WcAuthCode != null)
                    {
                        //更新使用状态
                        StringBuilder _dbSql = new StringBuilder("");
                        _dbSql.Append("update wc_auth_code set IsUsed=1 where ");
                        _dbSql.AppendFormat(" phoneSf='{0}' and code='{1}'", _PendPhoneSf, code);
                        var Paras = new List<SugarParameter>();
                        await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);
                        Output.LoginRet = 1;
                        Output.LoginMsg = "验证码正确";
                        Output.Oauser = null;
                        Output.token = null;
                        Output.expireTime = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else
                    {
                        Output.LoginRet = 0;
                        Output.LoginMsg = "验证码错误";
                    }
                }
            }
            catch (Exception ex)
            {
                Output.LoginRet = 0;
                Output.LoginMsg = "验证码错误";
                new LoggEx().errlog("VerifyCode()->异常:" + ex.ToString());
            }
            return Output;
        }
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        #endregion

        #region 临时日志写入
        [NonAction]
        void setlog(string str)
        {
            string name = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            string rootPath = Directory.GetCurrentDirectory();
            string path = $@"{rootPath}/logs/Wechat";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (FileStream fs = new FileStream(path + "/" + name, FileMode.Append))
            {
                str = "\r\n日期：" + DateTime.Now.ToString() + "\r\n消息：" + str;
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(str);
                sw.Flush();
                sw.Close();
            }
        }
        #endregion

        #region 切换当前登录使用单位
        /// <summary>
        /// 切换当前登录使用单位
        /// </summary>
        /// <param name="openId">微信openId</param>
        /// <param name="companyId">所选使用单位</param>
        /// <returns></returns>
        [HttpPost("ChangeLogin")]
        [AllowAnonymous]
        [Consumes("application/x-www-form-urlencoded")]
        public async Task<WeChatUserLoginOutput> ChangeLogin(string openId,string companyId)
        {
            WeChatUserLoginOutput Output = new WeChatUserLoginOutput();
            try
            {
                string tenantDbName = PARK.App.Configuration["ConnectionStrings:DBName"];
                string tenantId = PARK.App.Configuration["ConnectionStrings:ConfigId"];
                var entity = await _db.Queryable<EmployeeWechatEntity>().FirstAsync(p => p.OpenId == openId && p.CompanyId== companyId);
                if (entity != null)
                {
                    var eyeInfo = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == entity.EmployeeId);
                    if (entity.IsAudit == 1)
                    {
                        if (eyeInfo.AccStatus == 1 || eyeInfo.AccStatus == 3)
                        {
                            #region 生成token
                            //登录成功时 判断单点登录信息            
                            var tokenTimeout = 129600;// await _sysConfigService.GetInfo("SysConfig", "tokentimeout");//token过期时间
                            // 生成Token令牌
                            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                                {
                                        { ClaimConst.CLAINM_USERID, entity.WId},
                                        { ClaimConst.CLAINM_ACCOUNT, entity.OpenId },
                                        { ClaimConst.CLAINM_REALNAME, entity.RealName },
                                        { ClaimConst.CLAINM_ADMINISTRATOR, 0 },
                                        { ClaimConst.TENANT_ID, tenantId },
                                        { ClaimConst.TENANT_DB_NAME, tenantDbName },
                                        { ClaimConst.CLAINM_USER_KIND, "1" } //C端用户
                                }, tokenTimeout);
                            var httpContext = _httpContextAccessor.HttpContext;
                            // 设置Swagger自动登录
                            httpContext.SigninToSwagger(accessToken);
                            // 生成刷新Token令牌
                            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 30);
                            // 设置刷新Token令牌
                            httpContext.Response.Headers["x-access-token"] = refreshToken;
                            #endregion

                            //更新主认证账号
                            var Paras = new List<SugarParameter>();
                            StringBuilder _dbSql = new StringBuilder("update base_employee_wechat set IsMain=1");
                            _dbSql.AppendFormat(" where wId='{0}'", entity.WId);
                            await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);

                            StringBuilder sdbSql = new StringBuilder("update base_employee_wechat set IsMain=0");
                            sdbSql.AppendFormat(" where OpenId='{0}' and wId!='{1}'", openId, entity.WId);
                            await _db.Ado.ExecuteCommandAsync(sdbSql.ToString(), Paras);
                            //检测是否启用人脸
                            var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(companyId);
                            if (_appInfo != null && _appInfo.uni_is > 0)
                            {
                                Output.isUseface = 1;  //启用
                            }
                            else
                            {
                                Output.isUseface = 0; //不启用
                            }
                            //已绑定,账户状态可用
                            Output.LoginRet = 1;
                            Output.LoginMsg = "已认证通过";
                            Output.Oauser = entity;
                            Output.token = "Bearer " + accessToken;
                            Output.expireTime = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd HH:mm:ss");
                            Output.authTsMenu = eyeInfo.AuthTsMenu;
                        }
                        else
                        {
                            //账户状态,当前不可用
                            Output.LoginRet = 0;
                            Output.LoginMsg = "所绑卡户状态不可用";
                            Output.Oauser = entity;
                            Output.token = "";
                            Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                            Output.authTsMenu = 0;
                        }
                    }
                    else if (entity.IsAudit == 0)
                    {
                        //已绑定
                        Output.LoginRet = 0;
                        Output.LoginMsg = "未认证,请先认证身份";
                        Output.Oauser = entity;
                        Output.token = "";
                        Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                        Output.authTsMenu = 0;
                    }
                    else if (entity.IsAudit == 2)
                    {
                        //已绑定
                        Output.LoginRet = 2;
                        Output.LoginMsg = "已提交认证,待审批中";
                        Output.Oauser = entity;
                        Output.token = "";
                        Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                        Output.authTsMenu = 0;
                    }
                }
                else
                {
                    Output.LoginRet = 0;
                    Output.LoginMsg = "请认证身份";
                    Output.Oauser = entity;
                    Output.token = "";
                    Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                    Output.authTsMenu = 0;
                }
            }
            catch (Exception ex)
            {
                Output.LoginRet = 0;
                Output.LoginMsg = "登入异常";
                Output.token = "";
                Output.expireTime = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
                Output.authTsMenu = 0;
                setlog("WeChatUserSignin()->登入异常:" + ex.ToString());
            }
            return Output;
        }
        #endregion

        #region 通过Code获取手机号
        /// <summary>
        /// 通过Code获取手机号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("getPhoneNumber")]
        [AllowAnonymous]
        public async Task<WeChatUserPhoneNumOutput> getPhoneNumber(string code)
        {
            WeChatUserPhoneNumOutput Output = new WeChatUserPhoneNumOutput();
            try
            {
                WechatUser Wu = new WechatUser();
                string appid = $"{App.Configuration["OAuth:routine:appid"]}";
                string appsecret = $"{App.Configuration["OAuth:routine:appSecret"]}";
                setlog("GetPhoneNumber->------code:" + code + ";APPID:" + appid + ";APPSECRET:" + appsecret);
                //获取token
                var ret = Wu.GetAccessToken(appid, appsecret);
                if (ret > 0 && Wu != null && !string.IsNullOrEmpty(Wu.access_token))
                {
                    ret = Wu.GetPhoneNumberFromCode(code, Wu.access_token);
                    if (ret > 0 && Wu != null && !string.IsNullOrEmpty(Wu.phoneNumber))
                    {
                        setlog("0->获取到用户->phoneNumber->" + Wu.phoneNumber);
                        Output.LoginRet = 1;
                        Output.LoginMsg = "获取用户手机号成功";
                        Output.phoneNumber = Wu.phoneNumber;
                    }
                    else
                    {
                        Output.LoginRet = 0;
                        Output.LoginMsg = "获取用户手机号失败";
                        Output.phoneNumber = "";
                    }
                }
                else
                {
                    Output.LoginRet = -1;
                    Output.LoginMsg = "获取用户手机号失败";
                    Output.phoneNumber = "";
                }
            }
            catch (Exception ex)
            {
                Output.LoginRet = 0;
                Output.LoginMsg = "获取用户手机号失败";
                Output.phoneNumber = "";
                setlog("GetPhoneNumber()->获取用户手机号失败,异常:" + ex.ToString());
            }
            setlog("GetPhoneNumber()->请求返回:" + JsonConvert.SerializeObject(Output));
            return Output;
        }
        #endregion

        #region 阿里云短信
        /// <summary>
        /// 发送（阿里云短信）
        /// </summary>
        /// <param name="smsModel"></param>
        /// <returns></returns>
        public static SmsMessageModel SendSmsByAli(SmsModel smsModel)
        {
            try
            {
                IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", smsModel.keyId, smsModel.keySecret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                CommonRequest request = new CommonRequest();
                request.Method = MethodType.POST;
                request.Domain = "dysmsapi.aliyuncs.com";
                request.Version = "2017-05-25";
                request.Action = "SendSms";
                request.AddQueryParameters("PhoneNumbers", smsModel.mobileAli);
                request.AddQueryParameters("SignName", smsModel.signName);
                request.AddQueryParameters("TemplateCode", smsModel.templateId);
                request.AddQueryParameters("TemplateParam", smsModel.templateParamAli);

                CommonResponse response = client.GetCommonResponse(request);
                return JsonConvert.DeserializeObject<SmsMessageModel>(Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (Exception ex)
            {
                return new SmsMessageModel();
            }
        }
        /// <summary>
        /// 消息处理机制
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string MessageHandle(string Code)
        {
            string result = "";
            switch (Code)
            {
                case "OK":
                    //短信发送成功
                    result = "OK";
                    break;
                case "isp.RAM_PERMISSION_DENY":
                    result = "RAM权限DENY";
                    break;
                case "isv.OUT_OF_SERVICE":
                    result = "业务停机";
                    break;
                case "isv.PRODUCT_UN_SUBSCRIPT":
                    result = "未开通云通信产品的阿里云客户";
                    break;
                case "isv.PRODUCT_UNSUBSCRIBE":
                    result = "产品未开通";
                    break;
                case "isv.ACCOUNT_NOT_EXISTS":
                    result = "账户不存在";
                    break;
                case "isv.ACCOUNT_ABNORMAL":
                    result = "账户异常    ";
                    break;
                case "isv.SMS_TEMPLATE_ILLEGAL":
                    result = "短信模板不合法";
                    break;
                case "isv.SMS_SIGNATURE_ILLEGAL":
                    result = "短信签名不合法";
                    break;
                case "isv.INVALID_PARAMETERS":
                    result = "参数异常";
                    break;
                case "isv.MOBILE_NUMBER_ILLEGAL":
                    result = "非法手机号";
                    break;
                case "isv.MOBILE_COUNT_OVER_LIMIT":
                    result = "手机号码数量超过限制";
                    break;
                case "isv.TEMPLATE_MISSING_PARAMETERS":
                    result = "模板缺少变量";
                    break;
                case "isv.BUSINESS_LIMIT_CONTROL":
                    result = "业务限流";
                    break;
                case "isv.INVALID_JSON_PARAM":
                    result = "JSON参数不合法，只接受字符串值";
                    break;
                case "isv.PARAM_LENGTH_LIMIT":
                    result = "参数超出长度限制";
                    break;
                case "isv.PARAM_NOT_SUPPORT_URL":
                    result = "不支持URL";
                    break;
                case "isv.AMOUNT_NOT_ENOUGH":
                    result = "账户余额不足";
                    break;
                case "isv.TEMPLATE_PARAMS_ILLEGAL":
                    result = "模板变量里包含非法关键字";
                    break;
            }
            return result;
        }
        #endregion
    }
}
